package com.archgeek.java.biz;

import com.google.common.collect.Queues;
import org.apache.commons.lang3.RandomUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author pizhihui
 * @date 2023-12-02 17:08
 */
public class ArrayBlockingQueueTest {

    public static void main(String[] args) throws InterruptedException {


        ArrayBlockingQueue<Integer> q1 = new ArrayBlockingQueue(10000);

        HashSet list = new HashSet();

        // 遍历线程
        new Thread(() -> {

            for (int i = 0; i < 10000; i++) {

                sleep(1, 3);

//                List<Integer> res = new ArrayList<>();
//                Iterator<Integer> iterator = q1.iterator();
//                while (iterator.hasNext()) {
//                    Integer next = iterator.next();
//                    res.add(next);
//                }


                Integer peek = q1.peek();

                Object[] array = list.toArray();

                System.out.println("---------读取线程队列个数是=" + list.size() + ",当前内容是=" + Arrays.toString(array));

            }

        }).start();


        // 存取线程
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                sleep(3, 5);
                q1.offer(i);
                System.out.println("存入线程的数据是:+" + i + "当前队列数=" + q1.size());
            }
        }).start();

        TimeUnit.SECONDS.sleep(5);


        // 取线程
        new Thread(() -> {
            while (true) {
                System.out.println("===========读取线程,读取的数据是:等待.................");
                try {
                    Queues.drain(q1, list, 20, 1, TimeUnit.MINUTES);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("===========读取线程,读取的数据是:" + Arrays.toString(list.toArray()));
                list.clear();
                System.out.println("===========读取线程,读取的数据是清空");

            }

        }).start();


    }

    private static void sleep(int start, int end) {
        try {
            TimeUnit.SECONDS.sleep(RandomUtils.nextInt(start, end));
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
